import socket
import threading

def handle_receive(client_socket):
    while True:
        try:
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                print("客户端已断开连接。")
                break
            print(f"客户端说: {data}")
        except ConnectionResetError:
            print("客户端异常断开连接。")
            break
    client_socket.close()

def handle_send(client_socket):
    while True:
        try:
            msg = input()
            client_socket.send(msg.encode('utf-8'))
        except (ConnectionResetError, BrokenPipeError):
            print("连接已断开，无法发送消息。")
            break
    client_socket.close()

def main():
    host = '0.0.0.0'
    port = 12345

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(1)
    print("服务器已启动，等待客户端连接...")

    client_socket, addr = server_socket.accept()
    print(f"客户端 {addr} 已连接。")

    receive_thread = threading.Thread(target=handle_receive, args=(client_socket,))
    send_thread = threading.Thread(target=handle_send, args=(client_socket,))

    receive_thread.start()
    send_thread.start()

    receive_thread.join()
    send_thread.join()

    server_socket.close()
    print("服务器已关闭。")

if __name__ == "__main__":
    main()